<style lang="scss" scoped>
	@import '../../assets/login.scss';
</style>

<template>
	<div class="login-container">
		<van-nav-bar title="修改密码" left-text="返回" left-arrow @click-left="$router.back()" />
		<div class="title" style="margin-top:0.3rem;">
			<p class="text">修改密码</p>
		</div>
		<van-form class="form" @submit="edit">
			<div class="form-item">
				<van-field v-model="form.oldPassword" label="旧密码" name="oldPassword" type="password"
					placeholder="请输入旧密码" size="large" :rules="[{required:true}]" center clearable></van-field>
			</div>
			<div class="form-item">
				<van-field v-model="form.newPassword" label="新密码" name="newPassword" type="password"
					placeholder="请输入新密码" size="large" :rules="[{required:true}]" center clearable></van-field>
			</div>
			<div class="form-item">
				<van-field v-model="form.repeatNewPassword" label="确认新密码" name="repeatNewPassword" type="password"
					placeholder="请再次输入新密码" size="large" :rules="[{required:true,validator:validatorPassword}]" center
					clearable></van-field>
			</div>
			<div class="btn-box">
				<van-button type="default" color="#179AFE" block>确认修改</van-button>
			</div>
		</van-form>
	</div>
</template>

<script>
	import {
		editPassword
	} from '../../api/index';

	export default {
		name: 'EditPassword',
		data() {
			return {
				form: {
					oldPassword: '',
					newPassword: '',
					repeatNewPassword: ''
				}
			};
		},
		methods: {
			validatorPassword(val) {
				return this.form.newPassword === this.form.repeatNewPassword;
			},
			async edit() {
				try {
					const params = {
						oldpasswd: this.form.oldPassword,
						newpasswd: this.form.newPassword
					};

					const {
						errorcode,
						errormsg
					} = await editPassword(params);

					if (errorcode == 0) {
						this.$toast('修改成功!');
						this.$store.dispatch('handleLogout');
						this.$router.replace('/login');
					} else {
						this.$toast(errormsg);
					}
				} catch (error) {
					console.log(error);
				}
			}
		}
	};
</script>
